package com.bf.electroplating.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 签名工具类
 * 
 * @author system
 * @since 2025-01-11
 */
public class SignUtil {

    private static final String APP_SECRET = "bcc2b6db2fd54ca08d35414145713f13";

    /**
     * 生成签名参数
     * 
     * @param body 请求体
     * @return 签名后的参数字符串
     */
    public static String generateParams(Object body) {
        Map<String, String> data = new HashMap<>();
        data.put("timestamp", String.valueOf(System.currentTimeMillis()));
        data.put("v", "1.0");
        data.put("body", JSON.toJSONString(body));
        data.put("sign", sign(data));
        return JSON.toJSONString(data);
    }

    /**
     * 生成签名
     * 
     * @param data 数据
     * @return 签名
     */
    private static String sign(Map<String, String> data) {
        // 请求参数按照【属性名】字典升序排序后，按照属性名+属性值拼接
        String signStr = data.keySet().stream()
                .sorted()
                .map(it -> String.format("%s%s", it, data.get(it)))
                .collect(Collectors.joining(""));

        // 拼接后的结果首尾加上appSecret
        String finalSignStr = APP_SECRET + signStr + APP_SECRET;

        // MD5加密并转为大写
        return DigestUtils.md5Hex(finalSignStr).toUpperCase();
    }
}